#include "vin_det.h"
#include "power.h"
#include "heat.h"
#include "adc.h"
#include "ui_event.h"

bool vin_ok_status;
bool ovp_status;
uint8_t ovp_cnt;

void vin_detect_handle(void)
{
    uint16_t vinv;
    uint8_t ovs;

    /* usb cable plugging detect*/
    if (POWER_IS_DCIN_OK()) {
        vin_ok_status = true;
    } else {                        /* UV or OV */
        vin_ok_status = false;
    }

    MFP2 |= 0x0C;     /* P11 AN4 */
    /* over voltage detect */
    if (!heating_flag) {
        vinv = adc_get_value_mv(0x04);

        if (POWER_IS_DCIN_OK()) {
            ovs = 0;
            ovp_status = 0;
        } else {
            if (vinv >= VIN_OVP_THR) {
                ovs = 1;
            } else if ((vinv >= VIN_UNOVP_THR) && ovp_status) {
                ovs = 1;
            } else {
                ovs = 0;
            }
        }

        if (ovp_status != ovs) {
            if (++ovp_cnt >= VIN_OVP_DEB_NUM) {
                ovp_status = ovs;
                ui_event |= 1 << UI_EVENT_NTC_ABN;
            }
        } else {
            ovp_cnt = 0;
        }
    }
}


bool vin_is_ok(void)
{
    if (vin_ok_status) {
        return 1;
    }

    return 0;
}